from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from app.config.database_config import PgManager
from app.services.booking_service import BookingService
from app.schemas.booking import (
    BookingCreate,
    BookingResponse,
    BookingUpdate,
    BookingWithDetails,
    SeatSelection,
    BookingCancellation
)

import logging
logger = logging.getLogger(__name__)

router = APIRouter(prefix="/bookings", tags=["bookings"])

def get_booking_service(db: Session = Depends(PgManager.get_db_static)) -> BookingService:
    return BookingService(db)

@router.post("/", response_model=BookingResponse)
def create_booking(
    booking: BookingCreate,
    service: BookingService = Depends(get_booking_service)
):
    """创建新的机票预订"""
    new_booking = service.create_booking(booking)
    if not new_booking:
        raise HTTPException(status_code=400, detail="无法创建预订，请检查乘客、航班信息或座位可用性")
    return new_booking

@router.get("/", response_model=List[BookingWithDetails])
def get_bookings(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    service: BookingService = Depends(get_booking_service)
):
    """获取所有预订列表"""
    bookings = service.get_bookings(skip=skip, limit=limit)
    result = []
    for booking in bookings:
        result.append(BookingWithDetails(
            id=booking.id,
            booking_number=booking.booking_number,
            passenger={
                "id": booking.passenger.id,
                "first_name": booking.passenger.first_name,
                "last_name": booking.passenger.last_name,
                "email": booking.passenger.email,
                "phone": booking.passenger.phone
            },
            flight={
                "id": booking.flight.id,
                "flight_number": booking.flight.flight_number,
                "departure_city": booking.flight.departure_city,
                "arrival_city": booking.flight.arrival_city,
                "departure_time": booking.flight.departure_time,
                "arrival_time": booking.flight.arrival_time,
                "departure_airport": booking.flight.departure_airport,
                "arrival_airport": booking.flight.arrival_airport
            },
            seat_number=booking.seat_number,
            booking_status=booking.booking_status,
            booking_date=booking.booking_date,
            price=booking.price
        ))
    return result


@router.get("/search", response_model=List[BookingWithDetails])
def search_bookings(
        booking_number: Optional[str] = Query(None, min_length=2, description="预订号"),
        passenger_name: Optional[str] = Query(None, min_length=2, description="乘客姓名"),
        flight_number: Optional[str] = Query(None, min_length=2, description="航班号"),
        service: BookingService = Depends(get_booking_service)
):
    """搜索预订（根据预订号、乘客姓名或航班号）"""
    if not any([booking_number, passenger_name, flight_number]):
        raise HTTPException(status_code=400, detail="至少需要提供一个查询条件")

    # 调用服务层方法进行查询
    bookings = service.search_bookings(
        booking_number=booking_number,
        passenger_name=passenger_name,
        flight_number=flight_number
    )

    if not bookings:
        raise HTTPException(status_code=404, detail="未找到匹配的预订")

    # 构建包含详细信息的响应
    result = [
        BookingWithDetails(
            id=booking.id,
            booking_number=booking.booking_number,
            passenger={
                "id": booking.passenger.id,
                "name": booking.passenger.name,
                "email": booking.passenger.email,
                "phone": booking.passenger.phone
            },
            flight={
                "id": booking.flight.id,
                "flight_number": booking.flight.flight_number,
                "departure_city": booking.flight.departure_city,
                "arrival_city": booking.flight.arrival_city,
                "departure_time": booking.flight.departure_time,
                "arrival_time": booking.flight.arrival_time,
                "departure_airport": booking.flight.departure_airport,
                "arrival_airport": booking.flight.arrival_airport
            },
            seat_number=booking.seat_number,
            booking_status=booking.booking_status,
            booking_date=booking.booking_date,
            price=booking.price
        ) for booking in bookings
    ]
    return result


@router.get("/{booking_number}", response_model=BookingWithDetails)
def get_booking_by_number(
    booking_number: str,
    service: BookingService = Depends(get_booking_service)
):
    """根据预订号获取预订详情"""
    booking = service.get_booking_by_number(booking_number)
    if not booking:
        raise HTTPException(status_code=404, detail="预订未找到")

    return booking

@router.get("/passenger/{passenger_id}", response_model=List[BookingWithDetails])
def get_bookings_by_passenger(
    passenger_id: int,
    service: BookingService = Depends(get_booking_service)
):
    """获取乘客的所有预订"""
    bookings = service.get_bookings_by_passenger(passenger_id)
    if not bookings:
        raise HTTPException(status_code=404, detail="该乘客暂无预订")

    result = []
    for booking in bookings:
        result.append(BookingWithDetails(
            id=booking.id,
            booking_number=booking.booking_number,
            passenger={
                "id": booking.passenger.id,
                "first_name": booking.passenger.first_name,
                "last_name": booking.passenger.last_name,
                "email": booking.passenger.email,
                "phone": booking.passenger.phone
            },
            flight={
                "id": booking.flight.id,
                "flight_number": booking.flight.flight_number,
                "departure_time": booking.flight.departure_time,
                "arrival_time": booking.flight.arrival_time,
                "departure_airport": booking.flight.departure_airport.code,
                "arrival_airport": booking.flight.arrival_airport.code
            },
            seat_number=booking.seat_number,
            booking_status=booking.booking_status,
            booking_date=booking.booking_date,
            price=booking.price
        ))
    return result

@router.get("/flight/{flight_id}/seats", response_model=List[str])
def get_available_seats(
    flight_id: int,
    service: BookingService = Depends(get_booking_service)
):
    """获取航班的可用座位"""
    seats = service.get_available_seats(flight_id)
    if seats is None:
        raise HTTPException(status_code=404, detail="航班未找到")
    return seats

@router.put("/{booking_number}/seat", response_model=BookingResponse)
def update_seat(
    booking_number: str,
    seat_selection: SeatSelection,
    service: BookingService = Depends(get_booking_service)
):
    """选择或更新座位"""
    updated_booking = service.update_seat(booking_number, seat_selection.seat_number)
    # logger.warning(updated_booking)
    if not updated_booking:
        raise HTTPException(status_code=400, detail="无法更新座位，座位可能已被占用或预订状态无效")
    return updated_booking

@router.put("/{booking_number}/cancel", response_model=BookingCancellation)
def cancel_booking(
    booking_number: str,
    service: BookingService = Depends(get_booking_service)
):
    """取消预订"""
    cancelled_booking = service.cancel_booking(booking_number)
    if not cancelled_booking:
        raise HTTPException(status_code=400, detail="无法取消预订，预订不存在或已取消")

    return BookingCancellation(
        message="预订已成功取消",
        booking={
            "booking_number": cancelled_booking.booking_number,
            "status": cancelled_booking.booking_status,
            "cancellation_date": cancelled_booking.updated_at
        }
    )

@router.get("/stats/overview")
def get_booking_stats(service: BookingService = Depends(get_booking_service)):
    """获取预订统计信息"""
    return service.get_booking_stats()